<template>
  <div id="home">
    <!-- 顶部导航栏 -->
    <van-nav-bar class="navbar" @click-left="onClickLeft" @click-right="onClickRight">
      <template #left>
        <van-icon name="wap-nav" class="left" />
      </template>
      <template #title>
        <div class="title">首页</div>
      </template>
      <template #right>
        <van-icon name="comment" class="right" color="#fff"/>
      </template>
    </van-nav-bar>
    <!-- 左侧的划栏 -->
    <van-popup v-model="popupShow" position="left" style="width: 80%; height: 100%" class="popup" @touchstart.native="start($event)" @touchmove.native="move($event)" @touchend.native="end">
      <slide></slide>
    </van-popup>
    <!-- 轮播图 -->
    <van-pull-refresh v-model="isLoading" @refresh="onRefresh">
      <van-swipe :autoplay="3000" class="lunbo">
        <van-swipe-item v-for="(image, index) in images" :key="index">
          <img v-lazy="image" class="lunboImg"/>
        </van-swipe-item>
      </van-swipe>
      <!-- 搜索框 -->
      <van-search
        v-model="search"
        placeholder="请输入搜索关键词"
        shape="round"
        background="transparent"
        @search="onSearch"
      />
      <!-- 点击悬赏任务按钮后出现的四个任务分类 -->
      <div class="publicFour" :class="{shortShow: isShow}" @click="publicShort">短时效</div>
      <div class="publicFour" :class="{jobShow: isShow}" @click="publicJob">兼职</div>
      <div class="publicFour" :class="{noticeShow: isShow}" @click="publicNotice">公告</div>
      <div class="publicFour" :class="{marketShow: isShow}" @click="publicMarket">市场</div>
      <!-- 发布悬赏任务按钮 -->
      <div class="public" @click="publicClick" v-show="!isLoading">
        <van-icon name="plus" class="publicPlus" />
      </div>
      <!-- 首页四个悬赏分类 -->
      <div class="classify">
        <div class="sort" @click="shortClick">
          <div>
            <van-image :src="require('../../assets/yuhangyuan.png')" class="Img"></van-image>
            短时效
          </div>
        </div>
        <div class="sort" @click="jobClick">
          <div>
            <van-image :src="require('../../assets/kongjianzhan.png')" class="Img"></van-image>
            兼职
          </div>
        </div>
        <div class="sort" @click="noticeClick">
          <div>
            <van-image :src="require('../../assets/huixing.png')" class="Img"></van-image>
            公告
          </div>
        </div>
        <div class="sort" @click="marketClick">
          <div>
            <van-image :src="require('../../assets/liuxing.png')" class="Img"></van-image>
            二手市场
          </div>
        </div>
      </div>
      <!-- 首页短时效类悬赏 -->
      <div class="shortTask">
        可选订单
      </div>
      <van-dropdown-menu style="width: 100px;position: absolute;right: 10px;" >
        <van-dropdown-item v-model="value" :options="option"  />
      </van-dropdown-menu>
      <div class="short" v-if="value == 0">
        <task-list v-for="(items, index) in profile" :key="index" :items="items" />
      </div>
      <div class="short" v-if="value == 1">
        <task-list v-for="(items, index) in sortCount()" :key="index" :items="items" />
      </div>
      <div class="short" v-if="value == 2">
        <task-list v-for="(items, index) in sortMoney()" :key="index" :items="items" />
      </div>
    </van-pull-refresh>
  </div>
</template>

<script>
import { Toast } from 'vant';
import Slide from '../../components/Slide'
import TaskList from '../../components/TaskList'

export default {
  name: 'Home',
  components: {
    Slide,
    TaskList
  },
  data() {
    return {
      popupShow: false, // 右划栏的显示
      images: [
        'https://ss1.bdstatic.com/70cFuXSh_Q1YnxGkpoWK1HF6hhy/it/u=1311085666,1887597967&fm=26&gp=0.jpg',
        'https://ss1.bdstatic.com/70cFvXSh_Q1YnxGkpoWK1HF6hhy/it/u=112290667,1179064404&fm=26&gp=0.jpg',
        'https://ss3.bdstatic.com/70cFv8Sh_Q1YnxGkpoWK1HF6hhy/it/u=972815750,4017429371&fm=26&gp=0.jpg'
      ], // 轮播图
      search: '', // 搜索的内容
      value: 0, // 默认排序
      option: [
        { text: '时间排序', value: 0 },
        { text: '距离排序', value: 1 },
        { text: '悬赏金排序', value: 2 },
      ], // 排序下拉选项
      profile: [
      ], // 发布悬赏任务的用户信息
      isShow: false, // 点击发布任务是否显示四个悬赏任务分类
      startX: 0, // 右划栏手指按下时的坐标
      translate: 0, // 右划栏手指移动时的坐标
      isLoading:false
    }
  },
  methods: {
     onRefresh() {
      setTimeout(() => {
       this.axios({
          method: "get",
          url: this.$store.state.url+"/order",
          headers:{
           'Authorization': localStorage.token
                }
      }).then((res) => {
        for(var i of res.data.data){
          i.img  = JSON.parse(i.img);
          i.imgCount = Object.keys(i.img);
          for(var t in i.imgCount){
            i.img[t] = "http://picture.105577.xyz/"+ i.img[t];
          }
          i.users.img = "http://picture.105577.xyz/"+ i.users.img;
          i.long = (parseInt (i.long))
        }
        
        this.profile = res.data.data;

      })
      Toast.loading({
        message: '加载中...',
        forbidClick: true,
      });
      this.axios({
        method: "get",
        url: this.$store.state.url+"/auth/user/info",
        headers:{
           'Authorization': localStorage.token
                }
      }).then((res) => {
        if(res.data.data.img){
        res.data.data.img = "http://picture.105577.xyz/"+res.data.data.img;
        }
        this.users = res.data.data;
        localStorage.user = JSON.stringify(this.users);
        this.$store.state.user =  res.data.data;
      })
        this.isLoading = false;
      }, 1000);
    },
    onClickLeft() {
      this.popupShow = true
    },
    onClickRight() {
      this.$router.push('/message')
    },
    start(e) {
      this.startX = e.touches[0].clientX;
    },
    move(e) {
      const popup = document.getElementsByClassName('popup')[0]
      this.translate = this.startX - e.touches[0].clientX;
      if (this.translate > 15) {
        popup.style.transform = "translate3d(" + "-" + this.translate + "px, -50%" + ',0' + ")";
      }
    },
    end() {
      const popup = document.getElementsByClassName('popup')[0]
      if (this.translate >= 100) {
        popup.style.transform = "";
        this.popupShow = false;
      } else {
        popup.style.transform = "translate3d(" + "0" + "px, -50%" + ',0' + ")";
      }
    },
    publicClick() {
      this.isShow = !this.isShow;
    },
    onSearch() {
      this.$router.push({
        name: 'search',
        params: {
          searchContent: this.search
        }
      })
    },
    shortClick() {
      this.$router.push({
       path: '/task',
       query:{
         num: 1
       }
      }).catch(err => err)
    },
    jobClick() {
      this.$router.push({
       path: '/task',
       query:{
         num: 2
       }
      }).catch(err => err)
    },
    noticeClick() {
       this.$router.push({
       path: '/task',
       query:{
         num: 3
       }
      }).catch(err => err)
    },
    marketClick() {
      this.$router.push({
       path: '/task',
       query:{
         num: 4
       }
      }).catch(err => err)
    },
    taskClick() {
      
    },
    publicShort() {
      this.$router.push('/publishshort').catch(err => err)
    },
    publicJob() {
      this.$router.push('/publishjob').catch(err => err)
    },
    publicNotice() {
      this.$router.push('/publishnotice').catch(err => err)
    },
    publicMarket() {
      this.$router.push('/publishmarket').catch(err => err)
    },
    sortMoney() {
      var _this = this;
        return _this.profile.slice().sort(function(x,y){
        if(x.money < y.money){ 
          return 1;
        }
        if(x.money > y.money){
          return -1;
        }
      })
    },
     sortCount() {
      var _this = this;
        return _this.profile.slice().sort(function(x,y){
        if(x.long&&y.long){
        if(x.long > y.long){ 
          return 1;
        }
        if(x.long < y.long){
          return -1;
        }
        }
      })
    },
    set(longitude,latitude){
        let params = new URLSearchParams();
        params.append('longitude',longitude)
        params.append('latitude',latitude)
        this.axios({
          method: "put",
          url: "http://xs.bigbaozi.club/api/v1/auth/user/address",
          headers:{
            'Authorization': localStorage.token
                  },
          params
      }).then((res) => {
        console.log(res.data);
      }).catch(err =>{
        console.log(err)
      })
    }
  },
  watch: {
    popupShow: {
      handler(newVal, oldVal) {
        if (newVal === true) {
          document.body.style.overflow = "hidden";
          document.body.style.height = "100vh"
        } else {
          document.body.style.overflow = "";
          document.body.style.height = ""
        }
      }
    }
  },
  created(){
    if(localStorage){
      this.axios({
          method: "get",
          url: this.$store.state.url+"/tencent/sign",
          headers:{
           'Authorization': localStorage.token
                }
      }).then((res) => {   
        localStorage.usersig=res.data.usersig;
        localStorage.userid=res.data.userid;  
      }).catch((err) => {
          console.log(err);
      })
    }
    this.axios({
          method: "get",
          url: this.$store.state.url+"/order",
          headers:{
           'Authorization': localStorage.token
                }
      }).then((res) => {
        for(var i of res.data.data){
          i.img  = JSON.parse(i.img);
          i.imgCount = Object.keys(i.img);
          for(var t in i.imgCount){
            i.img[t] = "http://picture.105577.xyz/"+ i.img[t];
          }
          i.users.img = "http://picture.105577.xyz/"+ i.users.img;
          i.long = (parseInt (i.long))
        }
        console.log(res.data.data)
        this.profile = res.data.data;

      })
      Toast.loading({
        message: '加载中...',
        forbidClick: true,
      });
      this.axios({
        method: "get",
        url: this.$store.state.url+"/auth/user/info",
        headers:{
           'Authorization': localStorage.token
                }
      }).then((res) => {
        if(res.data.data.img){
        res.data.data.img = "http://picture.105577.xyz/"+res.data.data.img;
        }
        this.users = res.data.data;
        localStorage.user = JSON.stringify(this.users);
        this.$store.state.user =  res.data.data;
      })
       if (navigator.geolocation) {
            //判断是否有这个对象
            navigator.geolocation.getCurrentPosition((pos)=>{
                console.log("经度：" + pos.coords.longitude + "纬度：" + pos.coords.latitude);
                  this.set(pos.coords.longitude+'',pos.coords.latitude+'')
            })
        } else {
            console.log("当前系统不支持GPS API")
        }
  },
  mounted(){
    if(localStorage.token){
       if (navigator.geolocation) {
            //判断是否有这个对象
          setInterval(()=>navigator.geolocation.getCurrentPosition((pos)=>{
                console.log("经度：" + pos.coords.longitude + "纬度：" + pos.coords.latitude);
                  this.set(pos.coords.longitude+'',pos.coords.latitude+'')
            }),100000);
        } else {
            console.log("当前系统不支持GPS API")
        }
    }
    
  },
}
</script>

<style scoped>
  .navbar {
    background: #66cd99;
    box-shadow: 0 0px 5px #9ad5a7;
    color: #9ad5a7;
  }
  .left {
    color: #fff;
    font-size: 20px
  }
  .title {
    color: #fff;
    font-size: 20px
  }
  .right {
    color: #fff;
    font-size: 20px
  }
  .lunbo {
    margin: 15px auto;
    width: 90%;
    height: 200px;
    border-radius: 10px;
  }
  .lunboImg {
    height: 200px;
    width: 100%
  }
  .popup {
    background: #9ad5a7;
  }
  .shortTask {
    width:100px;
    font-size:19px;
    font-weight:500;
    position:absolute;
    left:50%;
    right:50%;
    transform:translate(-50%,40%);
  }
  .publicFour {
    display: flex;
    justify-content: center;
    align-items: center;
    position: absolute;
    position: fixed;
    right: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    bottom: -20px;
    width: 60px;
    height: 60px;
    border-radius: 100%;
    box-shadow: 2px 2px 10px #99CC66;
    color: #ffffff;
    font-weight: 800;
    background: linear-gradient(45deg, #00f7ff, #00d5ff, #00b7ff,#0088ff);
    font-size: 15px;
    letter-spacing: 2px;
    opacity: 0;
    transition: 0.3s;
    z-index: 1999;
  }
  .shortShow {
    opacity: 1;
    transform: translate(-210%, -50%);
  }
  .jobShow {
    opacity: 1;
    transform: translate(-130%, -160%);
  }
  .noticeShow {
    opacity: 1;
    transform: translate(30%, -160%);
  }
  .marketShow {
    opacity: 1;
    transform: translate(110%, -50%);
  }
  .public {
    display: flex;
    justify-content: center;
    align-items: center;
    position: fixed;
    right: 50%;
    left: 50%;
    bottom:-10px;
    transform: translate(-50%, -50%);
    width: 55px;
    height: 55px;
    border-radius: 100%;
    box-shadow: 2px 2px 10px #313131;
    color: #ffffff;
    text-align: center;
    background: #FF6666;
    z-index: 2000;
  }
  .publicPlus {
    font-size: 30px
  }
  .classify {
    display: flex;
    flex-wrap: wrap;
    justify-content: center;
    align-items: center;
    width: 100%;
    margin-bottom: 5px;
    border-radius: 10px;
    background: transparent;
  }
  .sort {
    display: flex;
    justify-content: center;
    align-items: center;
    text-align: center;
    padding: 10px;
    width: 70px;
    background: transparent;
    color: white;
    font-size: 13px;
    font-weight: 900;
  }
  .Img {
    width: 60px;
    height: 60px
  }
  .short {
    width: 100%;
    padding: 50px 0 0 0;
    margin-bottom: 65px;
    border-radius: 10px;
    background: #ffffff;
    float: left;
  }
  .img {
    float: left;
    margin: 0 20px 0 0;
  }
  .name {
    float: left;
    padding: 0;
    margin: 5px 0;
    width: 200px;
  }
  .signature {
    float: left;
    font-size: 13px;
    padding: 0;
    margin: 0;
    width: 200px;
  }
  .money {
    position: absolute;
    font-weight: 600;
    font-size: 20px;
    color: #ff000d;
  }
</style>